import React, { useState, useEffect } from 'react';
import { Table, Button, Switch, message, Modal, Space, Input, Tag } from 'antd';
import { SearchOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { userApi } from '../../api';

const { confirm } = Modal;

const Users = () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [searchText, setSearchText] = useState('');

  // 获取用户列表
  const fetchUsers = async (page = 0, size = 10) => {
    setLoading(true);
    try {
      const response = await userApi.getAllUsers(page, size);
      if (response.success) {
        setUsers(response.data.content || []);
        setPagination({
          current: page + 1,
          pageSize: size,
          total: response.data.totalElements || 0
        });
      } else {
        message.error(response.message || '获取用户列表失败');
      }
    } catch (error) {
      console.error('获取用户列表错误:', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    fetchUsers();
  }, []);

  // 处理表格变化
  const handleTableChange = (pagination) => {
    fetchUsers(pagination.current - 1, pagination.pageSize);
  };

  // 处理用户状态变更
  const handleStatusChange = (checked, record) => {
    const newStatus = checked ? 1 : 0;
    
    confirm({
      title: `确定要${checked ? '启用' : '禁用'}用户 "${record.username}" 吗?`,
      icon: <ExclamationCircleOutlined />,
      content: `${checked ? '启用' : '禁用'}后，该用户${checked ? '将能' : '将无法'}登录系统`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await userApi.updateUserStatus(record.id, newStatus);
          if (response.success) {
            message.success(`${checked ? '启用' : '禁用'}用户成功`);
            // 更新本地用户列表
            setUsers(users.map(user => 
              user.id === record.id ? { ...user, status: newStatus } : user
            ));
          } else {
            message.error(response.message || `${checked ? '启用' : '禁用'}用户失败`);
          }
        } catch (error) {
          console.error('更新用户状态错误:', error);
          message.error(`${checked ? '启用' : '禁用'}用户失败`);
        }
      }
    });
  };

  // 处理搜索
  const handleSearch = () => {
    // 这里应该调用后端搜索API，但目前后端可能没有实现搜索功能
    // 所以我们先在前端进行简单过滤
    if (searchText) {
      const filteredUsers = users.filter(user => 
        user.username.toLowerCase().includes(searchText.toLowerCase()) ||
        user.email.toLowerCase().includes(searchText.toLowerCase())
      );
      setUsers(filteredUsers);
    } else {
      // 如果搜索框为空，重新获取所有用户
      fetchUsers(pagination.current - 1, pagination.pageSize);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => (
        <Tag color={role === 'ADMIN' ? 'red' : 'blue'}>
          {role === 'ADMIN' ? '管理员' : '普通用户'}
        </Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status, record) => (
        <Switch 
          checkedChildren="启用" 
          unCheckedChildren="禁用" 
          checked={status === 1}
          onChange={(checked) => handleStatusChange(checked, record)}
          disabled={record.role === 'ADMIN'} // 不允许禁用管理员
        />
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (text) => new Date(text).toLocaleString()
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <h2>用户管理</h2>
        <Space>
          <Input
            placeholder="搜索用户名/邮箱"
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            onPressEnter={handleSearch}
            style={{ width: 200 }}
          />
          <Button 
            type="primary" 
            icon={<SearchOutlined />} 
            onClick={handleSearch}
          >
            搜索
          </Button>
        </Space>
      </div>
      
      <Table
        columns={columns}
        dataSource={users}
        rowKey="id"
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
      />
    </div>
  );
};

export default Users; 